<template>
  <div class="class-settlement-container">
    <div class="settlement-header">
      <h2>班级结算详情</h2>
    </div>

    <!-- 收入项区域 -->
    <div class="settlement-section">
      <h3 class="section-title">收入项</h3>
      <el-table
        :data="incomeItems"
        border
        size="mini"
        class="settlement-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="培训费用项目" align="center">
          <template #default="scope">
            {{ getProjectName(scope.row.project) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity"></el-table-column>
        <el-table-column label="单价" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.price || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.subtotal || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"></el-table-column>
      </el-table>
    </div>

    <!-- 收入合计行 -->
    <div class="settlement-section">
      <el-table
        border
        size="mini"
        class="summary-table"
      >
        <el-table-column label="收入合计" align="right" :colspan="5">
          <template #default>
            <span class="summary-label">收入合计：</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center">
          <template #default>
            <span class="summary-value">{{ formatCurrency(incomeTotal) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 支出项区域 -->
    <div class="settlement-section">
      <h3 class="section-title">支出项</h3>
      <el-table
        :data="expenseItems"
        border
        size="mini"
        class="settlement-table"
      >
        <el-table-column label="序号" type="index" width="60" align="center"></el-table-column>
        <el-table-column label="培训费用项目" align="center">
          <template #default="scope">
            {{ getProjectName(scope.row.project) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity"></el-table-column>
        <el-table-column label="单价" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.price || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.subtotal || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"></el-table-column>
      </el-table>
    </div>

    <!-- 支出合计和利润行 -->
    <div class="settlement-section">
      <el-table
        border
        size="mini"
        class="summary-table"
        :data="summaryData"
      >
        <el-table-column label="项目" align="right" :colspan="5">
          <template #default="scope">
            <span class="summary-label">{{ scope.row.label }}：</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center">
          <template #default="scope">
            <span :class="['summary-value', scope.row.class]">{{ formatCurrency(scope.row.value) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { listClassPaymentSettlement } from "@/api/training/classPaymentSettlement.js";

export default {
  name: 'ClassSettlementDetail',
  props: {
    // 仅接收班级ID参数
    classId: {
      type: String,
      required: true, // 强制要求传入classId
      default: ""
    }
  },
  dicts: ["training_cost_project"],
  data() {
    return {
      costProjectDict: [], // 费用项目字典
      incomeItems: [], // 收入项数据
      expenseItems: [] // 支出项数据
    }
  },
  computed: {
    // 收入合计
    incomeTotal() {
      return this.incomeItems.reduce((total, item) => total + (item.subtotal || 0), 0)
    },
    // 支出合计
    expenseTotal() {
      return this.expenseItems.reduce((total, item) => total + (item.subtotal || 0), 0)
    },
    // 利润（收入-支出）
    profit() {
      return this.incomeTotal - this.expenseTotal;
    },
    // 合计与利润数据
    summaryData() {
      return [
        { label: '支出合计', value: this.expenseTotal, class: 'expense-total' },
        { label: '利润', value: this.profit, class: this.profit >= 0 ? 'profit-positive' : 'profit-negative' }
      ]
    }
  },
  watch:{
    classId:{
      handler(newVal){
        this.loadDictData();
        this.getList();
      }
    }
  },
  created() {

  },
  methods: {
    // 加载费用项目字典
    loadDictData() {
      this.costProjectDict = this.dict?.type?.training_cost_project || [];
    },

    // 根据班级ID获取结算数据
    async getList() {
      try {
        const res = await listClassPaymentSettlement({
          trainingClassId: this.classId
        });
        console.log(res)
        if (res.code === 200) {
          this.incomeItems = [];
          this.expenseItems = [];

          res.rows.forEach(backendItem => {
            const frontItem = {
              id: backendItem.classPaymentSettlementId,
              project: backendItem.trainingCostProject,
              quantity: backendItem.num,
              price: backendItem.price,
              subtotal: backendItem.cost,
              remark: backendItem.remark || ""
            };

            // 区分收入（2）和支出（1）
            if (backendItem.costType === "2") {
              this.incomeItems.push(frontItem);
            } else if (backendItem.costType === "1") {
              this.expenseItems.push(frontItem);
            }
          });
        } else {
          this.$message.error(`结算数据加载失败：${res.msg}`);
        }
      } catch (err) {
        this.$message.error("结算列表接口调用失败");
        console.error("列表加载错误：", err);
      }
      console.log(this.incomeItems)
      console.log(this.expenseItems)

    },

    // 格式化金额为人民币格式
    formatCurrency(amount) {
      return '¥' + Number(amount).toFixed(2);
    },

    // 根据项目编码获取项目名称
    getProjectName(value) {
      const project = this.costProjectDict.find(item => item.value === value);
      return project ? project.label : value;
    }
  }
}
</script>

<style scoped>
.class-settlement-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.settlement-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.settlement-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.settlement-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  padding-bottom: 5px;
  border-bottom: 1px dashed #e8e8e8;
}

.settlement-table, .summary-table {
  width: 100%;
  margin-bottom: 5px;
}

.summary-label {
  font-weight: 500;
  margin-right: 10px;
  color: #333;
}

.summary-value {
  font-weight: 500;
}

/* 不同合计项的颜色区分 */
.summary-value:not(.expense-total):not(.profit-positive):not(.profit-negative) {
  color: #1890ff; /* 收入合计 */
}

.expense-total {
  color: #f56c6c; /* 支出合计 */
}

.profit-positive {
  color: #52c41a; /* 利润为正 */
}

.profit-negative {
  color: #f56c6c; /* 利润为负 */
}
</style>
